<?php

namespace V1\Model;

use Think\Exception;
use Think\Model;
use Common\Common\Tools;

class MemberProfileModel extends Model
{
    protected $tableName = 'member_profile';

    /**
     * 注册时 设置用户ID
     * @param int $userid
     * @return bool
     * @throws Exception
     */
    public function set_member_profile($userid)
    {
        $data['userid'] = intval($userid);
        $data['location'] = 1;
        $data['gold'] = 0;
        $data['frozen_gold'] = 0;
        $data['total_gold'] = 0;
        $result = $this->add($data);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 通过用户ID获取用户名
     * @param string $uid 用户id
     */
    public function get_uid_by_name($uid)
    {
        $data = D('MemberProfile')->field('truename,nickname')->where(array('userid' => $uid))->find();
        if (!empty($data['truename'])) {
            $name = $data['truename'];
        } else {
            $name = $data['nickname'];
        }
        return $name;
    }

    /**
     * 通过邀请码判断邀请码是否存在
     * @param string $code 邀请码
     * @return int
     * @throws Exception
     */
    public function check_apply_code($code)
    {
        $data = D('MemberProfile')->field('truename,nickname')->where(array('apply_code' => $code))->count();
        if ($data > 0) {
            return 1;   //已存在
        } else {
            return 0;   //未存在
        }
    }

    /**
     * 邀请码加积分
     * @param string $uid 用户id
     * @param string $code 邀请码
     * @return bool
     * @throws Exception
     */
    public function add_apply_code_score($uid, $code)
    {
        $map['apply_code'] = $code;
        $map_two['userid'] = $uid;
        $integral_add = $this->where($map)->setInc('score', 100);
        $integral_add_two = $this->where($map_two)->setInc('score', 100);
        if (false === $integral_add || false === $integral_add_two) {
            throw new Exception();
        } else {
            return true;
        }
    }

    /**
     * 获取用户信息
     * @param $userid [用户id]
     * @param string $field [去除参数]
     * @param bool $type [去除反选]
     * @return mixed
     */
    public function get_member_profile($userid, $field = '', $type = true)
    {
        $area = new AreaModel();
        $map['userid'] = !empty($userid) ? $userid : "";
        $member_profile = $this->where($map)->field($field, $type)->select();
        if ($member_profile) {
            foreach ($member_profile as $k => $v) {
                $z = $area->get_area_full_name_from_area_id($v['areaid']);
                $member_profile[$k]['area_name'] = Tools::arr2str($z, ' ');
            }
        }
        return $member_profile;
    }

    /**
     * 获取邀请码
     * @param $userid [用户id]
     * @param string $field [去除参数]
     * @param bool $type [去除反选]
     * @return mixed
     */
    public function get_member_code($userid)
    {
        $map['userid'] = $userid;
        $code = $this->where($map)->field('apply_code')->find();
        return $code;
    }

    /**
     * 通过用户ID判断邀请码是否存在
     * @param $uid
     * @return mixed
     */
    public function check_uid_apply_code($uid)
    {
        $map['userid'] = $uid;
        $bool = $this->where($map)->select();
        return !empty($bool) ? true : false;
    }

    /**
     * 邀请码生成函数
     * @param $uid
     * @param $length
     * @param string $chars
     * @return string
     */
    public function apply_code_rand($uid, $length, $chars = '0123456789abcdefghijklmnopqrstuvwxyz')
    {
        $hash = '';
        $max = strlen($chars) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        $map['userid'] = $uid;
        $request = $this->where($map)->setField('apply_code', $hash);
        if ($request) {
            return $this->get_member_code($uid);
        } else {
            return 0;
        }
    }

    /**
     * 获取用户金额
     * @param $userid [用户ID]
     * @return mixed
     */
    public function get_member_gold_int($userid)
    {
        $map['userid'] = $userid;
        $gold = $this->where($map)->field('gold')->find();
        return $gold['gold'];
    }

    /**
     * 会员积分(累加)
     * @param int $uid [用户id]
     * @param $module [积分需要添加的模块积分]
     * @param int $type [类型 如果$type值为0则从配置文件中调用module否则直接调用传入的module]
     * @return bool
     */
    public function add_score($uid, $module, $type = 0)
    {
        if ($uid) {
            //如果tag
            $type != 0 ? $score = $module : $score = C("SCORE")[$module];
            $map['userid'] = $uid;
            $info = $this->where($map)->setInc('score', $score);
            return $info;
        } else {
            return false;
        }
    }

    /**
     * 提交问题后减去金币进入冻结字段
     * @param $userid
     * @param $gold
     * @return bool
     */
    public function scrubtract_gold($userid, $gold)
    {
        $map['userid'] = $userid;
        if ($userid) {
            $this->where($map)->setDec('gold', $gold);//提问问题者 减金币
            $this->where($map)->setInc('frozen_gold', $gold);//提问问题者 冻结金币
            return true;
        } else {
            return false;
        }
    }

    /**
     * 会员金币(累加)
     * @param $userid [用户ID]
     * @param $gold [问题悬赏的金币]
     * @return mixed
     */
    public function add_gold($userid, $gold)
    {
        if ($userid) {
            $map['userid'] = $userid;
            $data = $this->where($map)->setInc('gold', $gold);
            return $data ? true : false;
        }
    }

    /**
     * 会员金币(减)
     * @param $userid [用户ID]
     * @param $gold [问题悬赏的金币]
     * @return mixed
     */
    public function minus_gold($userid, $gold)
    {
        if ($userid) {
            $map['userid'] = $userid;
            $data = $this->where($map)->setDec('frozen_gold', $gold);
            return $data ? true : false;
        }
    }

    /**
     * 获取用户详情
     * @param $id [当前用户id]
     * @param $type [查询类型]
     * @param $userid [关注用户id,用于查询是否被关注]
     * @return string
     */
    public function get_user_details_common($id, $type = '', $userid = null)
    {
        if (!empty($id)) {
            $member_model = new MemberModel();
            $integral_model = new IntegralModel();
            $member_fans_model = new MemberFansModel();
            $member_profile_model = new MemberProfileModel();
            $expert_profile_model = new ExpertProfileModel();
            //获取用户详细资料（头像/擅长作物/地址/个人简介）
            $member = $member_model->getMember($id);
            if (!empty($member)) {
                $member_field = 'reg_ip,logintimes,reg_time,last_login_ip,last_login_time,status,fans_nums,agreed_times,agreed_times2,artical_nums,formula_nums';
                $member_profile = $member_profile_model->get_member_profile($id, $member_field);
                $expert_field = 'name,expert_type,good_at_crop,good_at_area';
                $expert_profile = $expert_profile_model->get_expert_profile($id, $expert_field);
                foreach ($member as $k => $v) {
                    $member[$k]['is_expert'] = 0;
                    if (count($expert_profile) > 0) {
                        $member[$k]['expert_profile'] = $expert_profile;
                        $member[$k]['is_expert'] = 1;
                    }
                    if (count($member_profile) > 0) {
                        $member[$k]['member_profile'] = $member_profile[0];
                        $grade = $integral_model->set_member_grade(intval($member_profile[0]['score']), $id);
                        $member[$k]['grade'] = !empty($grade) ? $grade['grade_id'] : "";
                    } else {
                        $member[$k]['member_profile'] = ['area_name' => '暂无', 'avatar' => 'Uploads/image/defaultx20.jpg', 'is_ok' => 0];
                    }
                }
                $data['profile'] = $member;
                switch ($type) {
                    case 'fans':
                        $question_answer_model = new QuestionAnswerModel();
                        //获取用户关注,同意数量
                        //关注数量
                        $data['attention'] = $member_fans_model->get_attention_number($id);
                        //同意数量
                        $data['agree'] = $question_answer_model->agree($id);
                        //是否被关注
                        $data['is_attention'] = $member_fans_model->is_follow($id, $userid);
                        break;
                    case 'follow':
                        break;
                    case 'arc_answers':
                        break;
                    default:
                        $question_ask_model = new QuestionAskModel();
                        $question_adopt_model = new QuestionAdoptModel();
                        $question_answer_model = new QuestionAnswerModel();
                        //获取/是否被关注用户关注/粉丝/好评率/积分/提问/回答/同意/不同意
                        $data['is_attention'] = $member_fans_model->is_follow($id, $userid);
//                        var_dump($data['is_attention']);exit;
                        $data['attention'] = $member_fans_model->get_attention_number($id);
                        $data['fans'] = $member_fans_model->get_fans_number($id);
                        //好评率
                        $data['favorable'] = $question_answer_model->add_adoption_rates($id);
                        //提问数量
                        $question = $question_ask_model->get_id_by_ask_list($id);
                        $data['question'] = count($question);
                        //回答数量
                        $huida = $question_ask_model->get_uid_by_answer_list($id);
                        $data['answer'] = count($huida);
                        //同意数量
                        $data['agree'] = $question_answer_model->agree($id);
                        //不同意
                        $data['dis_agree'] = $question_answer_model->dis_agree($id);
                        //勋章
                        $data['medal'] = $expert_profile_model->return_rank($id);
                        //金币
                        $data['gold'] = $member_profile_model->get_member_gold_int($id);
                        //被采纳
                        $data['accepted'] = $question_adopt_model->get_grade($id);
                        break;
                }
                return $data;
            } else {
                return "没有用户信息";
            }
        } else {
            return "没有userid";
        }
    }

    /**
     * 获取用户问题列表详情
     * @param $id
     * @param string $type
     * @param null $userid
     * @return string
     */
    public function get_user_details_ask_list($id, $type = '', $userid = null)
    {
        if (!empty($id)) {
            $member_model = new MemberModel();
            $integral_model = new IntegralModel();
            $member_profile_model = new MemberProfileModel();
            $expert_profile_model = new ExpertProfileModel();
            $question_answer_model = new QuestionAnswerModel();
            //获取用户详细资料（头像/擅长作物/地址/个人简介）
            $member = $member_model->getMember($id);
            if (!empty($member)) {
                $member_field = 'userid,avatar,truename,areaid,address,memberships,gold,score';
                $member_profile = $member_profile_model->get_member_profile($id, $member_field, false);
                $expert_field = 'name,expert_type,good_at_crop,good_at_area';
                $expert_profile = $expert_profile_model->get_expert_profile($id, $expert_field);
                foreach ($member as $k => $v) {
                    $member[$k]['is_expert'] = 0;
                    if (count($member_profile) > 0) {
                        $member[$k]['member_profile'] = $member_profile[0];
                    } else {
                        $member[$k]['member_profile'] = ['area_name' => '暂无', 'avatar' => 'Uploads/image/defaultx20.jpg'];
                    }
                    if (count($expert_profile) > 0) {
                        $member[$k]['expert_profile'] = $expert_profile;
                        $member[$k]['is_expert'] = 1;
                        $member[$k]['member_profile']['memberships'] = $expert_profile['expert_type'];
                    }
                }
                $data['profile'] = $member;
                switch ($type) {
                    case 'get_code':
                        $grade = $integral_model->set_member_grade($member_profile[0]['score'], $id);
                        $data['grade'] = !empty($grade) ? $grade : "";
                        break;
                    case 'follow':
                        $member_fans_model = new MemberFansModel();
                        //关注数量
                        $data['attention'] = $member_fans_model->get_attention_number($id);
                        //是否被关注
                        $data['is_attention'] = $member_fans_model->is_follow($id, $userid);
                        //同意数量
                        $data['agree'] = $question_answer_model->agree($id);
                        break;
                    default:
                        $grade = $integral_model->set_member_grade($member_profile[0]['score'], $id);
                        $data['grade'] = !empty($grade) ? $grade : "";
                        $data['medal'] = $expert_profile_model->return_rank($id);
                        //好评率
                        $data['favorable'] = $question_answer_model->add_adoption_rates($id);
                        break;
                }
                return $data;
            } else {
                return "";
            }
        } else {
            return "没有userid";
        }
    }
}
